package com.huafeng.config;

import com.huafeng.utils.SpringContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;


/**
 * @author 花风
 * @date 2022/11/30 21:29
 * @Description 定时任务配置
 */
@Configuration
public class ScheduledConfig implements SchedulingConfigurer {
    //用来统计每天每个人私聊使用自动回复的次数
    public static Map<String,Integer> privateCount = new ConcurrentHashMap<>();

    //用来统计每天每个群使用自动回复的次数
    public static Map<String,Integer> groupCount = new ConcurrentHashMap<>();

    //记录撤回的消息
    public static List<String> messageList = new LinkedList<>();


    //每天23点59分59秒刷新次数
    @Scheduled(cron = "59 59 23 * * ? ")
    public void refresh(){
        //help GC
        privateCount = null;
        groupCount = null;

        privateCount = new ConcurrentHashMap<>();
        groupCount = new ConcurrentHashMap<>();
    }


    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(() ->{
            BotPropertiesConfig botPropertiesConfig = SpringContextUtils.getBean(BotPropertiesConfig.class);
            //获取参数
            String savePath = botPropertiesConfig.getSave_path();
            Boolean isSave = botPropertiesConfig.getIs_save();

            if (isSave){
                try(FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath) + "\\"
                        + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                        + ".txt")) {

                    String message = String.join("", messageList);

                    //重置
                    messageList = null;
                    messageList = new LinkedList<>();

                    fileOutputStream.write(message.getBytes(StandardCharsets.UTF_8));
                    fileOutputStream.flush();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        },triggerContext -> {
                    //查询数据库  获得该类的cron表达式
            BotPropertiesConfig botPropertiesConfig = SpringContextUtils.getBean(BotPropertiesConfig.class);
            String cron = botPropertiesConfig.getCron();
                    // CronTrigger实现了Trigger
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
        });
    }
}
